<html>
<body>
	<head>
	<meta charset="utf-8">
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	</head>
	<body>
	<div id="root">
	</div>
	<script>

// 模板嵌套		
let users = [
	{name: '张', age: '22'},
	{name: '李', age: '33'},
	{name: '王', age: '44'},
]
const tmpl = (users) => {
return `<table>
		<tr>
			<td>姓名</td>
			<td>年龄</td>
		</tr>
		${users.map((item) => `<tr>
			<td>${item.name}</td>
			<td>${item.age}</td>
		</tr>`).join('') }
	</table>`
}
let table = tmpl(users)
	 $('#root').append(table)

// 模板自身封装方法

let str1 = 'return ' + '`Hello ${name}!`';
let func = new Function('name', str1);
console.log(func('Jack')) // "Hello Jack!"


///模板实例1


let data = ['1模板内容111','2模板内容222','3模板内容333']
		//原始模板
var template = `
<ul>
  <% for(var i=0; i < data.length; i++) { %>
    <li><%= data[i] %></li>
  <% } %>
</ul>`;


		// 替换成表达式字符串
var evalExpr = /<%=(.+?)%>/g;
var expr = /<%([\s\S]+?)%>/g;

templateX = template
  .replace(evalExpr, '`); \n  echo( $1 ); \n  echo(`')
  .replace(expr, '`); \n $1 \n  echo(`');

templateX = 'echo(`' + templateX + '`);';

console.log('替换的模板字符串')
console.log(templateX)

//封装成函数字符串
var script =
`(function parse(data){
  var output = "";

  function echo(html){
    output += html;
  }

  ${ templateX }

  return output;
})`;
console.log('封装成函数字符串')
console.log(script)


function compile(template){
  var evalExpr = /<%=(.+?)%>/g;
  var expr = /<%([\s\S]+?)%>/g;

  template = template
    .replace(evalExpr, '`); \n  echo( $1 ); \n  echo(`')
    .replace(expr, '`); \n $1 \n  echo(`');

  template = 'echo(`' + template + '`);';

  var script =
  `(function parse(data){
    var output = "";

    function echo(html){
      output += html;
    }

    ${ template }

    return output;
  })`;

  return script;
}
var parse = eval(compile(template));
let innerHTML = parse(data);

let List = new Function( data,compile(template) )
 $('#root').append(List)
	</script>
	</body>
</html>
